﻿using System.Data;
using ESSManageService.Common.Helper;
using Serilog;
using Serilog.Events;
using SqlSugar;

namespace ESSManageService.Common
{
    public class MyContext
    {
        private SqlSugarScope _db;

        private static string _connectionString = AppSettings.GetValue("DBConnectionString").ToString();
        /// <summary>
        /// 连接字符串 
        /// ESSManageService
        /// </summary>
        public static string ConnectionString
        {
            get 
            {
                if (string.IsNullOrEmpty(_connectionString))
                    _connectionString = AppSettings.GetValue("DBConnectionString").ToString();
                return _connectionString;
            }
            set { _connectionString = value; }
        }
        /// <summary>
        /// 数据连接对象 
        /// ESSManageService 
        /// </summary>
        public SqlSugarScope Db
        {
            get { return _db; }
            private set { _db = value; }
        }

        /// <summary>
        /// 功能描述:构造函数
        /// 作　　者:ESSManageService
        /// </summary>
        public MyContext(ISqlSugarClient sqlSugarClient)
        {
            if (string.IsNullOrEmpty(_connectionString))
                throw new ArgumentNullException("数据库连接字符串为空");

            _db = sqlSugarClient as SqlSugarScope;

            var SqlLogLevel = AppSettings.app(new string[] { "Serilog", "MinimumLevel", "SqlLogLevel" }).ObjToString();
            
            if(AppSettings.app(new string[] { "Serilog", "MinimumLevel", "IsOpenSqlLog" }).ObjToBool())
                switch (SqlLogLevel)
                {
                    case "Information":
                        _db.Aop.OnLogExecuting = (sql, pars) =>
                        {
                            // 打印 SQL 语句和参数
                            Console.WriteLine($"执行的 SQL 语句: {sql}");
                            Console.WriteLine("参数:");
                            foreach (var param in pars)
                            {
                                Console.WriteLine($"  {param.ParameterName}: {param.Value}");
                            }
                            // 使用 Serilog 记录日志
                            Log.Information("执行的 SQL 语句: {Sql}, 参数: {@Parameters}", sql, pars);
                        };
                        break;
                    case "Result":
                        _db.Aop.OnLogExecuted = (sql, pars) =>
                        {
                            // 打印 SQL 语句和参数
                            Console.WriteLine($"执行的 SQL 语句: {sql}");
                            Console.WriteLine("参数:");
                            foreach (var param in pars)
                            {
                                Console.WriteLine($"  {param.ParameterName}: {param.Value}");
                            }
                            // 使用 Serilog 记录日志
                            Log.Information("Executed SQL: {Sql} 参数: {@Parameters} in {CostTime} ms", sql, pars);
                        };
                        break;
                    case "Error":
                        _db.Aop.OnError = (exp) =>
                        {
                            // 打印 当 SQL 语句执行出错时，记录错误信息
                            // 使用 Serilog 记录日志
                            Log.Error(exp, "SQL execution error: {ErrorMessage}", exp.Message);
                        };
                        break;
                    default:
                        _db.Aop.OnLogExecuting = (sql, pars) =>
                        {
                            // 打印 SQL 语句和参数
                            Console.WriteLine($"执行的 SQL 语句: {sql}");
                            Console.WriteLine("参数:");
                            foreach (var param in pars)
                            {
                                Console.WriteLine($"  {param.ParameterName}: {param.Value}");
                            }
                            // 使用 Serilog 记录日志
                            Log.Information("执行的 SQL 语句: {Sql}, 参数: {@Parameters}", sql, pars);
                        };
                        break;
                }
                
        }


        #region 实例方法
        /// <summary>
        /// 功能描述:获取数据库处理对象
        /// 作　　者:ESSManageService
        /// </summary>
        /// <returns>返回值</returns>
        public SimpleClient<T> GetEntityDB<T>() where T : class, new()
        {
            return new SimpleClient<T>(_db);
        }
        /// <summary>
        /// 功能描述:获取数据库处理对象
        /// 作　　者:ESSManageService
        /// </summary>
        /// <param name="db">db</param>
        /// <returns>返回值</returns>
        //public SimpleClient<T> GetEntityDB<T>(SqlSugarClient db) where T : class, new()
        //{
        //    return new SimpleClient<T>(db);
        //}



        #endregion


        #region 根据实体类生成数据库表
        /// <summary>
        /// 功能描述:根据实体类生成数据库表
        /// 作　　者:ESSManageService
        /// </summary>
        /// <param name="blnBackupTable">是否备份表</param>
        /// <param name="lstEntitys">指定的实体</param>
        public void CreateTableByEntity<T>(bool blnBackupTable, params T[] lstEntitys) where T : class, new()
        {
            Type[] lstTypes = null;
            if (lstEntitys != null)
            {
                lstTypes = new Type[lstEntitys.Length];
                for (int i = 0; i < lstEntitys.Length; i++)
                {
                    T t = lstEntitys[i];
                    lstTypes[i] = typeof(T);
                }
            }
            CreateTableByEntity(blnBackupTable, lstTypes);
        }

        /// <summary>
        /// 功能描述:根据实体类生成数据库表
        /// 作　　者:ESSManageService
        /// </summary>
        /// <param name="blnBackupTable">是否备份表</param>
        /// <param name="lstEntitys">指定的实体</param>
        public void CreateTableByEntity(bool blnBackupTable, params Type[] lstEntitys)
        {
            if (blnBackupTable)
            {
                _db.CodeFirst.BackupTable().InitTables(lstEntitys); //change entity backupTable            
            }
            else
            {
                _db.CodeFirst.InitTables(lstEntitys);
            }
        }
        #endregion


        #region 静态方法

        ///// <summary>
        ///// 功能描述:获得一个DbContext
        ///// 作　　者:ESSManageService
        ///// </summary>
        ///// <returns></returns>
        //public static MyContext GetDbContext()
        //{
        //    return new MyContext();
        //}

        /// <summary>
        /// 功能描述:设置初始化参数
        /// 作　　者:ESSManageService
        /// </summary>
        /// <param name="strConnectionString">连接字符串</param>
        /// <param name="enmDbType">数据库类型</param>
        public static void Init(string strConnectionString, SqlSugar.DbType enmDbType = SqlSugar.DbType.SqlServer)
        {
            _connectionString = strConnectionString;
        }

        /// <summary>
        /// 功能描述:获取一个自定义的DB
        /// 作　　者:ESSManageService
        /// </summary>
        /// <param name="config">config</param>
        /// <returns>返回值</returns>
        public static SqlSugarScope GetCustomDB(ConnectionConfig config)
        {
            return new SqlSugarScope(config);
        }
        /// <summary>
        /// 功能描述:获取一个自定义的数据库处理对象
        /// 作　　者:ESSManageService
        /// </summary>
        /// <param name="sugarClient">sugarClient</param>
        /// <returns>返回值</returns>
        public static SimpleClient<T> GetCustomEntityDB<T>(SqlSugarScope sugarClient) where T : class, new()
        {
            return new SimpleClient<T>(sugarClient);
        }
        /// <summary>
        /// 功能描述:获取一个自定义的数据库处理对象
        /// 作　　者:ESSManageService
        /// </summary>
        /// <param name="config">config</param>
        /// <returns>返回值</returns>
        public static SimpleClient<T> GetCustomEntityDB<T>(ConnectionConfig config) where T : class, new()
        {
            SqlSugarScope sugarClient = GetCustomDB(config);
            return GetCustomEntityDB<T>(sugarClient);
        }
        #endregion
    }
}
